﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;
namespace AsyncCallback
{
   public class CalculatorClient
    {
       IAsyncResult m_AsyncResult;

       public void AsyncAdd(int argument1,int argument2)
       {
           Calculator calculator = new Calculator();
           DispatchAdd(calculator, argument1, argument2);
           //int result = GetResult();
           //Debug.Assert(result == argument1 + argument2);
       }

       void DispatchAdd(Calculator calculator, int number1, int number2)
       {
           BinaryOperation oppDel = calculator.Add;
           m_AsyncResult = oppDel.BeginInvoke(number1, number2, OnMethodCompletion, null);
       }

       void OnMethodCompletion(IAsyncResult asyncResult)
       {
           AsyncResult resultObj = asyncResult as AsyncResult;
           Debug.Assert(resultObj.EndInvokeCalled == false);
           BinaryOperation oppDel = resultObj.AsyncDelegate as BinaryOperation;
           try
           {
               int result = 0;
               result = oppDel.EndInvoke(asyncResult);
               Trace.WriteLine("操作后返回:" + result);
           }
           catch (Exception e)
           {
               Trace.WriteLine("异常:" + e.Message);
           }
       }

       int GetResult()
       {
           int result = 0;
           AsyncResult asyncResult = (AsyncResult)m_AsyncResult;
           BinaryOperation oppDel = (BinaryOperation)asyncResult.AsyncDelegate;
           Debug.Assert(asyncResult.EndInvokeCalled == false);
           result = oppDel.EndInvoke(m_AsyncResult);
           return result;
       }

       public void AsyncDivide(int argument1, int argument2)
       {
           Calculator calculator = new Calculator();
           BinaryOperation oppDel = calculator.Divide;
           oppDel.BeginInvoke(argument1, argument2, OnMethodCompletion, null);
       }
    }
}
